import RightClickMenu from './index.vue'
import { h, render } from 'vue'

let menuInstance = null
let seed = 1
const createMenuInstance = (e, data) => {
  if (menuInstance) {
    menuInstance.destroy()
  }
  menuInstance = null

  const container = document.createElement('div')
  const body = document.body
  const props = {
    data,
    onClose: () => {
      if (menuInstance) {
        menuInstance.destroy()
      }
    },
  }
  const vnode = h(
    RightClickMenu,
    props
  )
  render(vnode, container)

  body.appendChild(container.firstElementChild)

  const menuNode = vnode.el
  // menuNode的高度和宽度
  const {offsetWidth, offsetHeight} = menuNode
  // body的可视区域的宽度
  const {clientWidth} = body
  // 取出右键点击时的坐标，clientX是距离左侧的位置，clientY是距离顶部的位置
  const {clientX, clientY} = e

  // 当前宽度大于菜单的宽度，说明正常设置菜单距离左边界的距离，即设置style.left，否则需要设置style.right组件距离可视区域右侧的距离
  const leftOrRight = clientWidth - clientX > offsetWidth ? 'left' : 'right'
  const offsetLeft = Math.abs(clientWidth - clientX)
  // 当前高度高于菜单的高度，说明可以正常设置菜单距离上边界的距离，即设置style.top，否则style.bottom
  const topOrBottom = window.innerHeight - clientY > offsetHeight ? 'top' : 'bottom'
  // 设置left或者right的style
  menuNode.style[leftOrRight] = leftOrRight === 'left' ? `${ clientX }px` : `${ offsetLeft }px`
  // 设置top或者bottom的style
  menuNode.style[topOrBottom] = topOrBottom === 'bottom' ? '2px' : `${ clientY }px`

  menuInstance = {
    id: seed++,
    destroy: () => {
      render(menuInstance = null, container)
    },
  }
  return menuInstance
}
export default createMenuInstance